package com.ciei.dpagm.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import java.lang.reflect.Field;
import java.util.List;

/**
 * Created by wzx on 11/8/2017.
 */
public class DHX {

    /**
     * 将普通LIST数据转换成GRID需要的列表数据
     * @param list
     * @param idField  id字段名称
     * @param dataField data区域字段名, 按js配置照顺序填写
     * @return
     */
    public static JSONObject getGridListJson(List list, ConvertInterface[] convs, String idField, String... dataField){
        try {
            JSONObject jsonObject = new JSONObject();
            if(list.size() == 0){
                return jsonObject;
            }
            Class cls = list.get(0).getClass();
            Field id = ClassUtil.getField(cls, idField.trim());
            Field[] data = new Field[dataField.length];
            for (int i = 0; i < data.length; i++) {
                data[i] = ClassUtil.getField(cls, dataField[i].trim());
            }
            JSONArray jsonArray = new JSONArray();
            for (Object item : list) {
                JSONObject row = new JSONObject();
                id.setAccessible(true);
                row.put("id", id.get(item));
                JSONArray dataJson = new JSONArray();
                for (Field f : data) {
                    f.setAccessible(true);
                    Object v =  f.get(item);
                    dataJson.add(v == null ?  "" : v + "");
                }
                row.put("data", dataJson);
                jsonArray.add(row);
            }
            jsonObject.put("rows", jsonArray);
            return jsonObject;
        }catch (Exception e){
            throw new RuntimeException(e);
        }
    }
}
